package net;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.apache.log4j.Logger;

import java.util.Arrays;

class TcpServerHandler extends ChannelInboundHandlerAdapter {
    private String str_id;
    private Logger logger = Logger.getLogger(TcpServerHandler.class);
    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        str_id = String.valueOf(ctx.channel().hashCode());
        logger.info("新连接");
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) {
        ctx.close();
        ConnManager.getManager().conn_remove(str_id);
        logger.info("连接中断");
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        ByteBuf byt = (ByteBuf) msg;
        byte[] data = new byte[byt.readableBytes()];
        byt.readBytes(data);
        logger.info("length:" + data.length + ":" + Arrays.toString(data));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        ctx.close();
        logger.info("exceptionCaught:" +  cause.getMessage());
    }

}
